package com.se.http;


import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.util.FileUtil;
import com.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hdu_huang
 * @date 2021/7/20 22:24.
 */

@Slf4j
public class HttpTest {

    //HttpURLConnection 实现简单的 GET/POST
    //cmd /k ""D:\bin\cmder_mini\vendor\init.bat""     鲁棒是Robust
    //HttpsURLConnection 1.信任系统提供的证书（权威CA颁发） 不需要改动代码  2.全部信任证书(不安全) 3.信任指定证书
    //NacosRestTemplate  JdkHttpClientRequest

    //http = request line(包括method，request uri，protocol version)) + header + message body[非get]
    public static void main(String[] args) throws Exception {

        //设置http https代理    -Dhttps.proxyHost=host -Dhttps.proxyPort=port    -Djava.net.useSystemProxies=true
        //https://docs.oracle.com/javase/8/docs/technotes/guides/net/properties.html
        //System.setProperty("http.proxyHost", "127.0.0.1");
        //System.setProperty("http.proxyPort", "7890");
        //System.setProperty("https.proxyHost", "127.0.0.1");
        //System.setProperty("https.proxyPort", "7890");
        //System.setProperty("java.net.useSystemProxies", "true"); //使用系统代理

        //socks5代理
        //System.setProperty("socksProxyHost", "127.0.0.1");
        //System.setProperty("socksProxyPort", "7890");

        //代理类
        //Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8080));
        //testHttpURLConnection(proxy);


        //testWebDav();




        String url1 = "https://httpbin.org/get?name=HYG";
        String url2 = "https://httpbin.org/delay/5";
        String url3 = "https://httpbin.org/post";
        String url4 = "https://httpbin.org/post?love=qian&love=hec&num=3";
        String url5 = "http://localhost:8080/hello?name=huang";

        HashMap<String, String> params = new HashMap<>();
        params.put("love", "hec");
        params.put("age", "23");


        params.put("jsonRequestData", "{     \"version\":\"1.0\",     \"charset\":\"UTF-8\",     \"sign\":\"见签名处理章节\",     \"signType\":\"SHA-256\",     \"reqData\":{                \"dateTime\":\"20160623101430\",             \"txCode\":\"FBPK\",                    \"branchNo\":\"0755\",          \"merchantNo\":\"002346\"     }  }");
        HttpResult httpResult = HttpApacheClient.postForm("https://b2b.cmbchina.com/CmbBank_B2B/UI/NetPay/DoBusiness.ashx", null, params);
        params.remove("jsonRequestData");





        String json = "{\"count\":1,\"content\":[{\"id\":1,\"createTime\":\"2021-06-21 10:48:41\",\"collegeId\":1,\"wechat\":1,\"ali\":0,\"collegeName\":\"杭州电子科技大学\"}]}";
//        HttpV1Client.HttpResult httpResult1 = HttpV1Client.postJson(url5, null, json);
//        testWeChatPayDelay();
        Map<String, Object> map = JsonUtil.fromJson(json, Map.class);


        //String result1= HttpUtil.get("https://www.baidu.com");
        String result= HttpUtil.post(url4, map);

        //HttpResult httpResult = HttpV1Client.postJson(url4, null, JsonUtil.toJson(params));

        HttpResponse res = HttpRequest.post(url3).formStr(params).execute();
        //String body = HttpUtil.createGet(url1).execute().body();
        System.out.println(result);


        //! 机器测试
        testGanDaoMachine();



    }

    public static void testGanDaoMachine(){
        String baseUrl = "https://api.gan-dao.com";
        String token = "/v1/app/token"; //token有效期为20小时，需要 app 端定期刷新
        String operate = "/v1/device/operate"; //操作滚筒
        String property = "/v1/device/getPropertyByName"; //获取设备属性  BXY6-5
        String reset = "/v1/device/reset"; //重置
        String bind = "/v1/device/bind";
        String unbind = "/v1/device/unbind"; //deviceId
        String cause = "/v1/device/getCautionList"; //设备告警查询接口 deviceId
        String isOnline = "/v1/device/isOnline"; //deviceId 是否在线

        //暂时忽略
        String drying = "/v1/device/drying";
        String deviceOrder = "/v1/deviceOrder";
        String pulseWash = "/v1/device/pulseWash"; //BXY6-5  BXYD6-5[有消毒]
        String shoeWash = "/v1/device/shoeWash"; //BXY6-5  1：常用/标准 2：轻污 3：重污 4：单脱 5：桶自洁

        //dev、test
        String appKey = "2643aefc-f524-4261-9320-1cac12949681";
        String appSecret = "6fa3dd7f-da5a-4afe-940c-d2c0dcbfc071";
        //online
        String appKey1 = "cb6a3878-2656-4ea7-ab14-3dc965d68792";
        String appSecret1 = "380765b3-664c-4706-8483-21a1df7a3a96";


        HashMap<String, String> params = new HashMap<>();

        params.put("appKey", appKey1);
        params.put("appSecret", appSecret1);

        //token
//        HttpResult httpResult = HttpApacheClient.postJson(baseUrl + token, null, JsonUtil.toJson(params));
//        System.out.println(httpResult);

        //token 过期 401[major]
        String secret = "eyJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2MzAwNDQ4NDIsInN1YiI6IjBmNzZmOWM5YjhhMjExNTMwZGIzMzc0YzBiMDE1YTY4OTk3MWE0ZjJmMDAxYzg4NDZlMmQ3YjcxYTg2YWYwNmNlOTFiMTk1ZGFlMTMwN2RjOTJkZjhmMTQxM2EyYzJkMmRlZGQ3MjNmNWMyOTUyMGNhY2MzYjMxODYyNGZkNTVjMmM0MmRiN2FlOWU2ZjVlY2UyMGE0YzlhNDkzOGM2YzU3MGZkYjJkNDU3ZmE5NGE0ODQ1MDBjM2Q4YjkwZWUwMmJkMTEyODkxZmViNTAzODdjOTBiMTAyODRjY2FmZWY1N2Y0N2EwMWU4YTEzNmQ2ZGQxZDgxYzc2NGQzOWFjMjhhODU1ZTBmOTJiMmFjYjcwNDc4YWZjODY0NzUwMGIyY2Y2NWM2ZmI1Y2IyNjc3MjI5YThlYWU2NTZhNWNmNDhiNjczM2M4MTA2NzEyOGMxZWMwOTU4ZDM4YWQ0ZDc3Y2MiLCJpc3MiOiJoeXBlcmNoYWluIiwiZXhwIjoxNjMwMTMxMjQyfQ.UMAoc0dgSnk8krD2XhE5htIM5S511UkmL9AOfUfyfGU";
        Map<String, String> header = Map.of("t-access-token", secret);

        params.put("deviceId", "867567049504483"); //滚筒 867567049504483 波轮 861251052257711
        params.put("deviceType", "GXY8"); //GXY8：滚筒8公斤洗衣机 GXY13-5 [只用区分滚筒和波轮]   BXY6-5
        params.put("washType", "4"); //1：标准 2快速洗 3大物 4单脱 5筒自洁....
        params.put("orderId", "0");
        params.put("disinfection", "false");

//        testBind(header);//绑定滚筒
//        testBoBind(header);//绑定波轮
//        testUnBind(header);

        //滚筒操作
//        HttpResult resultOp = HttpV1Client.postJson(baseUrl + operate, header, JsonUtil.toJson(params));
//        log.info("resultOp = {}", resultOp);

        //波轮操作 1：标准 2：速洗 3：大物 4：单脱 5：桶自洁
        params.put("deviceId", "861251052257711");
        params.put("washType", "4");
        params.put("deviceType", "BXY6-5");
        params.put("disinfection", "false");
        //HttpResult resultPulse = HttpApacheClient.postJson(baseUrl + pulseWash, header, JsonUtil.toJson(params));
        //log.info("resultPulse = {}", resultPulse);

//        HttpResult online = HttpV1Client.get(baseUrl + isOnline + "?deviceId=861251052257711", header, null);
//        log.info("online = {}", online);
//
//        HttpResult resultCause = HttpV1Client.get(baseUrl + cause + "?deviceId=861251052257711", header, null);
//        log.info("resultCause = {}", resultCause);

        //获取机器状态
//        params.put("property", "cyclePhaseCW"); //remainingTimeMM 剩余洗涤时间  cyclePhaseCW 机器运行状态  laundryCycleStatus 机器是否在运行 [false/true]
//        HttpResult resultProp = HttpApacheClient.postJson(baseUrl + property, header, JsonUtil.toJson(params)); //Map.of("property", "remainingTimeMM", "deviceId", "867567049504483", "deviceType", "GXY8")
//        log.info("resultProp = {}", resultProp);

//        Map map1 = JsonUtil.fromJson(resultProp.content, Map.class);

        //复位
//        HttpResult resultReset = HttpApacheClient.postJson(baseUrl + reset, header, JsonUtil.toJson(params));
//        log.info("resultReset = {}", resultReset);

    }

    public static void testBind(Map<String, String> header) {

        String baseUrl = "https://api.gan-dao.com";
        String bind = "/v1/device/bind";

        HashMap<String, String> params = new HashMap<>();
        params.put("deviceId", "867567049504483");//滚筒 867567049504483  波轮 865374034738438   861251052257711[海狸]
        params.put("address", "杭州新加坡科技园");
        params.put("deviceName", "5号楼2号机滚筒8kg");
        params.put("deviceNumber", "QH1002");
        params.put("devicePlace", "5号楼");
        params.put("deviceType", "GXY8"); //GXY8 BXY6-5
        params.put("machineId", "QH1002");
        params.put("qrCode", "https://baimi529.bmznkj.com/avappservice/wechat/wechatRedirect?entrance=1&washerNo=QH1002");

        HttpResult resultBind = HttpV1Client.postJson(baseUrl + bind, header, JsonUtil.toJson(params));
        log.info("resultBind = {}", resultBind);
    }

    public static void testBoBind(Map<String, String> header) {

        String baseUrl = "https://api.gan-dao.com";
        String bind = "/v1/device/bind";

        HashMap<String, String> params = new HashMap<>();
        params.put("deviceId", "861251052257711");//波轮 865374034738438   861251052257711[海狸]
        params.put("address", "杭州新加坡科技园");
        params.put("deviceName", "5号楼1号机滚筒5.5kg");
        params.put("deviceNumber", "QH1001");
        params.put("devicePlace", "5号楼");
        params.put("deviceType", "BXY6-5"); //GXY8 BXY6-5
        params.put("machineId", "QH1001");
        params.put("qrCode", "https://baimi529.bmznkj.com/avappservice/wechat/wechatRedirect?entrance=1&washerNo=QH1001");

        HttpResult resultBind = HttpV1Client.postJson(baseUrl + bind, header, JsonUtil.toJson(params));
        log.info("resultBind = {}", resultBind);
    }

    public static void testUnBind(Map<String, String> header) {

        String baseUrl = "https://api.gan-dao.com";
        String unbind = "/v1/device/unbind"; //deviceId

        HashMap<String, String> params = new HashMap<>();
        params.put("deviceId", "867567049504483");//滚筒 867567049504483  波轮 865374034738438

        HttpResult resultUnBind = HttpV1Client.get(baseUrl + unbind + "?deviceId=867567049504483", header, null);
        log.info("resultUnBind = {}", resultUnBind);

    }

    //测试微信支付延迟 first:500-600  100-200ms
    public static void testWeChatPayDelay() throws Exception {
        String xml = "<xml>\n" +
                "  <appid>wxb5e6a67817e7d882</appid>\n" +
                "  <mch_id>1557178711</mch_id>\n" +
                "  <nonce_str>9ug42eb8PG5w7LLE2Ksj54T153QbZzdA</nonce_str>\n" +
                "  <body>自助售货</body>\n" +
                "  <attach>佰米总部</attach>\n" +
                "  <out_trade_no>VM2021070718021611027372</out_trade_no>\n" +
                "  <total_fee>1</total_fee>\n" +
                "  <spbill_create_ip>127.0.0.1</spbill_create_ip>\n" +
                "  <notify_url>https://test-vend.bmznkj.com/v1/payment/wechat/callback</notify_url>\n" +
                "  <trade_type>JSAPI</trade_type>\n" +
                "  <sign>3E448FC36D59B22766D469B62CEAD730</sign>\n" +
                "  <profit_sharing>N</profit_sharing>\n" +
                "  <sub_appid>wx714c79ad31e09e01</sub_appid>\n" +
                "  <sub_mch_id>1558539021</sub_mch_id>\n" +
                "  <sub_openid>oNfei1IGTQUWQxyNs9T68RFqabts</sub_openid>\n" +
                "</xml>";

        String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";

        //预热
        long time = System.currentTimeMillis();
        HttpV2Client.postXml(url, null, xml);//HttpV1Client  HttpApacheClient  HttpV2Client
        long time2 = System.currentTimeMillis();
        HttpResult httpResult = HttpV2Client.postXml(url, null, xml);
        long time3 = System.currentTimeMillis();

        System.out.println(httpResult);
        log.error("first connect time = {} ms, keep-alive time = {}", time2 - time, time3 - time2);

    }


    public static void testHttpURLConnection(Proxy proxy) throws Exception {

        String url = "https://httpbin.org/post?love=qian";
        url = "http://www.google.com/post?love=qian";

        URL httpUrl = new URL(url);

        HttpURLConnection connection;
        if (proxy == null) {
            connection = (HttpURLConnection) httpUrl.openConnection();
        } else {
            connection = (HttpURLConnection) httpUrl.openConnection(proxy);
        }

        connection.setConnectTimeout(3000);
        connection.setReadTimeout(3000);
        connection.setRequestMethod("POST");

        //RequestHeader
        connection.addRequestProperty("Content-type", "application/application/x-www-form-urlencoded;charset=utf-8");
        //本次是否处理重定向
        connection.setInstanceFollowRedirects(true);

        //是否有body参数  会把GET变成POST
        connection.setDoOutput(true); //必须在connect之前
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write("name=hello".getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        connection.connect();

        //查看responseCode  200 301 400 500
        int responseCode = connection.getResponseCode();
        System.out.println("responseCode = " + responseCode);

        Map<String, List<String>> headerFields = connection.getHeaderFields();
        log.warn("headerFields = " + headerFields);

        InputStream inputStream;

        if (responseCode == 200 || responseCode == 302) {
            inputStream = connection.getInputStream();
        } else {
            inputStream = connection.getErrorStream();
        }

        FileUtil.lines(inputStream).forEach(System.out::println);
        connection.disconnect();
    }

    public static void testWebDav() throws Exception {

        String authHeader = "Authorization";
        String auth = "Basic MTE3MjQxNjM4NEBxcS5jb206YXZyamc1bnc0aXp3NnZiYg==";
        HashMap<String, String> stringMap = new HashMap<>();
        stringMap.put(authHeader, auth);


        final String Dav_Base_Url = "https://dav.jianguoyun.com/dav/";
        String username = "1172416384@qq.com";
        String password = "avrjg5nw4izw6vbb";
        String authString = username + ":" + password;
        String authStringEnc = Base64.getEncoder().encodeToString(authString.getBytes());
        String authHeaderValue = "Basic " + authStringEnc;


        String JSON = "{\n" +
                "\t\"dataVersion\":{\n" +
                "\t\t\"counter\":3,\n" +
                "\t\t\"timestamp\":1669627796266\n" +
                "\t},\n" +
                "\t\"topicConfigTable\":{\n" +
                "\t\t\"SCHEDULE_TOPIC_XXXX\":{\n" +
                "\t\t\t\"order\":false,\n" +
                "\t\t\t\"perm\":6,\n" +
                "\t\t\t\"readQueueNums\":18,\n" +
                "\t\t\t\"topicFilterType\":\"SINGLE_TAG\",\n" +
                "\t\t\t\"topicName\":\"SCHEDULE_TOPIC_XXXX\",\n" +
                "\t\t\t\"topicSysFlag\":0,\n" +
                "\t\t\t\"writeQueueNums\":18\n" +
                "\t\t}\n" +
                "\t}\n" +
                "}";

        //https://dav.jianguoyun.com/dav/  172416384@qq.com   avrjg5nw4izw6vbb
        //查询GET  新增PUT 删除DELETE    修改POST[501 Not Implemented]
        HttpResult httpResult = HttpV1Client.postJson(Dav_Base_Url + "chatgpt-next-web/test1.json", stringMap, JSON);

        System.out.println(httpResult);

    }

}
